package com.gua.exception;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gua.common.exception.BusinessExecption;
import com.gua.common.response.AjaxResult;
import com.gua.common.response.AjaxResultEnum;

import lombok.extern.slf4j.Slf4j;

/**
 * https://blog.csdn.net/weixin_43702146/article/details/121035514
 * 
 * @author huangjj
 *
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

	/**
	 * 参数错误拦截
	 * 
	 * @param e
	 * @return
	 */
	@ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public AjaxResult<Void> handlerParamException(MethodArgumentNotValidException ex) {
		log.error("handlerParamException", ex);
        List<ObjectError> allErrors = ex.getBindingResult().getAllErrors();
        String message = allErrors.stream()
        		.map(s -> s.getDefaultMessage())
        		.collect(Collectors.joining(";"));
        return new AjaxResult<>(AjaxResultEnum.PARAM_ERROR.getCode(), message);
    }
	
	@ExceptionHandler(BusinessExecption.class)
	@ResponseBody
    public AjaxResult<Void> handleCustomException(BusinessExecption ex) {
		log.error("handleCustomException", ex);
		return new AjaxResult<>(ex.getCode(), ex.getErrorMessage());
    }
    
    // 其他异常处理方法
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public AjaxResult<Void> handleException(Exception ex) {
    	log.error("handleException", ex);
    	return new AjaxResult<>(AjaxResultEnum.FAIL.getCode(), AjaxResultEnum.FAIL.getMsg());
    }

}
